﻿using System;
using System.ComponentModel;
using Caliburn.Micro;
using Action = System.Action;

namespace Zero.Frontend
{
    /// <summary>
    /// Allows execution of action in background as part of coroutine.
    /// </summary>
    public class AsyncAction : IResult
    {
        private readonly Action _action;

        /// <summary>
        /// Inicializes with specific action.
        /// </summary>
        /// <param name="action"></param>
        public AsyncAction(Action action)
        {
            _action = action;
        }

        void IResult.Execute(ActionExecutionContext context)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => _action();
            bw.RunWorkerCompleted +=
                (sender, e) =>
                _completed(this, new ResultCompletionEventArgs() { Error = e.Error, WasCancelled = e.Cancelled });
            bw.RunWorkerAsync();
        }

        private EventHandler<ResultCompletionEventArgs> _completed = delegate { };
        event EventHandler<ResultCompletionEventArgs> IResult.Completed
        {
            add { _completed += value; }
            remove { _completed -= value; }
        }
    }
}
